<template>
	<view>
		<u-popup :show="showPopupModal" round="24rpx" @close="showHandle()">
			<view class="title-nav">
				<view class="title-panel">
					<text class="font-color font-28 font-bold">感谢您的支持，本集解锁后可继续观看</text>
					<view class="flex ai-center" @click="tipsHandle()">
						<text class="font-color-3 font-28 mr-10">遇到问题</text>
						<u-icon name="question-circle" :color="fontColor3" size="28rpx"></u-icon>
					</view>
				</view>
				<template v-if="isPlayerPage && isOpenEpisodePriceSwitch">
					<view class="episode-panel">
						<view class="flex ai-center">
							<text class="font-32 font-color font-bold">{{ video_name }}</text>
							<text class="font-32 font-color font-bold ml-20">第{{ episode_number }}集</text>
						</view>
						<view class="flex ai-center">
							<text class="font-24 font-color-2">专享价</text>
							<text class="font-40 font-bold main-color">{{ episode_price }}</text>
							<text class="font-24 main-color">金币</text>
						</view>
					</view>
				</template>
				<view class="flex ai-center mt-20">
					<u-image src="/static/images/jinbi-small.png" width="40rpx" height="40rpx"></u-image>
					<text class="font-28 font-color-3 ml-10">余额：{{ coinTotal }}金币</text>
				</view>
			</view>
			<!-- 系统是IOS，则根据条件拉起支付 -->
			<template v-if="isIOS">
				<!-- 不是默认渠道 -->
				<!-- 后台小程序配置，允许IOS支付 -->
				<template v-if="!isDefaultChannel && canPayIOS">
					<view class="recharge-nav">
						<RechargeItem v-for="(item,index) in rechargeList" :key="item.id" :item="item"
							class="recharge-item-box" @onCreateOrder="createOrder" />
					</view>
				</template>
				<template v-else>
					<u-empty mode="permission" icon="http://cdn.uviewui.com/uview/empty/permission.png"
						text="由于相关规范，ios功能暂不可用" text-color="#999" text-size="26rpx" />
					<view class="pb-40"></view>
				</template>
			</template>

			<!-- 安卓直接支付 -->
			<template v-if="isAndroid">
				<view class="recharge-nav">
					<RechargeItem v-for="(item,index) in rechargeList" :key="item.id" :item="item"
						class="recharge-item-box" @onCreateOrder="createOrder" />
				</view>
			</template>

			<view class="tips-popup tips-panel">
				<view class="word">
					<text>*</text>
					<text>金币属于虚拟商品，一经购买不得退换;</text>
				</view>
				<view class="word">
					<text>*</text>
					<text>充值后金币可能有延迟，1小时内未到账请与客服联系。</text>
				</view>
			</view>


		</u-popup>

		<!-- 继续支付弹出层 -->
		<view class="continue-pay-popup">
			<u-popup :show="showContinuePay" bgColor="transparent" mode="center">
				<image class="back-img" src="/static/images/continue-pay-back.png"></image>
				<image class="cloase-img" src="/static/images/continue-pay-close.png" @click="continuePayHandleCloase">
				</image>
				<image class="btn-img" src="/static/images/continue-pay-btn.png" @click="continuePayHandleSubmit">
				</image>
				<text class="refuse-text" @click="continuePayHandleCloase">残忍拒绝</text>
			</u-popup>
		</view>

		<!-- 温馨提示弹出层 -->
		<view class="tips-popup">
			<u-popup :show="showTips" mode="center" @close="tipsHandle()">
				<view class="tips-title">
					<text></text>
					<text>温馨提示</text>
					<u-icon name="close" :color="fontColor" size="32rpx" @click="tipsHandle()"></u-icon>
				</view>
				<view class="word">
					<text>*</text>
					<text>金币属于虚拟商品，一经购买不得退换;</text>
				</view>
				<view class="word">
					<text>*</text>
					<text>人民币购买金币的比例以充值界面显示为准。</text>
				</view>
				<view class="word">
					<text>*</text>
					<text>充值后金币可能有延迟，1小时内未到账请与客服联系。</text>
				</view>
				<view class="word">
					<text>*</text>
					<text>使用金币充值服务时,请务必保证您已满18岁,属于完全民事行为能力人,您未满18岁但依然继续充值或其他与您的民事行为能力相适应的行为,将视为已取得监护人或者法定代理人的同意。</text>
				</view>
			</u-popup>
		</view>

		<!-- 再次查询虚拟支付弹出层 -->
		<!-- <view class="continue-pay-popup">
			<u-popup :show="againQueryShow" bgColor="#fff" mode="center" round="8rpx">
				<view class="again-nav">
					<text class="font-color font-32 pt-20">再次查询支付结果</text>
					<view class="main-btn" style="width: 80%; padding-top: 40rpx;">
						<u-button text="查询" type="primary" shape="circle" @click="wxVirtualOrderQueryFn()">
						</u-button>
					</view>
				</view>
			</u-popup>
		</view> -->

	</view>
</template>

<script>
import RechargeItem from '@/components/recharge-item/recharge-item.vue'
import {
  queryPackageTemplate,
  orderCreateCoin,
  orderCreateVip,
  wxVirtualOrderQuery
} from '@/api/index.js'
import colorMixins from '@/mixins/colorMixins.js'
import { headerParams } from '@/config/headerParams.js'
import storage from '@/utils/storage.js'
import { CHANNEL_ID } from '@/store/mutation-types.js'

export default {
  name: 'RechargePopup',
  mixins: [colorMixins],
  components: { RechargeItem },
  props: {
    showPopup: {
      type: Boolean,
      default: false
    },
    // 继续支付弹出层
    shouldContinuePay: {
      type: Boolean,
      default: false
    },
    // 正在播放的短剧库id
    video_id: {
      type: [Number, String],
      default: ''
    },
    // 正在播放的短剧库名称
    video_name: {
      type: String,
      default: ''
    },
    // 正在播放的剧集Id
    episode_id: {
      type: [Number, String],
      default: ''
    },
    // 正在播放的剧集数
    episode_number: {
      type: Number,
      default: 0
    },
    // 正在播放的剧集价格
    episode_price: {
      type: Number,
      default: 0
    },
  },
  data() {
    return {
      coinTotal: 0,
      rechargeList: [],
      showPopupModal: false,
      activeColor: -1,
      activeItem: {},
      showContinuePay: false,
      showTips: false,
      typeText: {
        1: '天',
        2: '月',
        3: '年',
        4: '永久'
      },
      againQueryShow: false,
      outTradeNo: undefined,
      againIntervalTime: null
    }
  },
  computed: {
    isIOS() {
      return this.$store.state.systemInfo.osName == 'ios'
    },
    isAndroid() {
      return this.$store.state.systemInfo.osName == 'android'
    },
    canPayIOS() {
      return this.$store.state.appConfig.is_ireg == 1
    },
    isDefaultChannel() {
      const nowChannelId = storage.get(CHANNEL_ID)
      const defaultChannelId = headerParams.pid
      return nowChannelId == defaultChannelId
    },
    // true是播放页面调用当前组件
    isPlayerPage() {
      return this.$props.video_id !== ''
    },
    // true显示剧集价格
    isOpenEpisodePriceSwitch() {
      const { episode_price_switch } = this.$store.state.appConfig
      console.log(this.$store.state.appConfig)
      return episode_price_switch == 1
    }
  },
  watch: {
    showPopup: {
      handler(val) {
        this.showPopupModal = val
        if (val) this.init()
      },
      immediate: true
    },
    againQueryShow: {
      handler(val) {
        if (val === false) {
          clearInterval(this.againIntervalTime)
          this.againIntervalTime = null
        }
      }
    }
  },
  methods: {
    async init() {
      const res = await queryPackageTemplate()
      const {
        coinPack,
        vipPack
      } = res.package
      const coinArr = coinPack.map(e => {
        const {
          price,
          bg_type,
          corner_style,
          corner_bg_style
        } = e
        // Number会自动去掉小数点后面的0
        e.price = Number(price)
        const isHighlight = bg_type === 1
        e.corner_style = isHighlight ? corner_style || 1 : corner_style
        e.corner_bg_style = corner_bg_style || 5
      
        return {
          ...e,
          isVip: false
        }
      })
      let vipArr = vipPack.map(e => {
        const {
          price,
          bg_type,
          corner_style,
          corner_bg_style
        } = e
        // Number会自动去掉小数点后面的0
        e.price = Number(price)
        const isHighlight = bg_type === 1
        e.corner_style = isHighlight ? corner_style || 1 : corner_style
        e.corner_bg_style = corner_bg_style || 1
        return {
          ...e,
          isVip: true
        }
      })
      if (!this.isPlayerPage) {
        // 我的>充值，只展示普通会员数据
        vipArr = vipArr.filter(e => e.vip_type === 1)
      }
      this.coinTotal = res.coin
      this.rechargeList = [...coinArr, ...vipArr].sort((a, b) => a.sort - b.sort)
    },

    showHandle() {
      this.showPopupModal = !this.showPopupModal
      this.$emit('update:showPopup', this.showPopupModal)
    },

    tipsHandle() {
      this.showTips = !this.showTips
    },

    async createOrder(item, index) {
      if (item) this.activeItem = item

      const _this = this
      const {
        id,
        isVip
      } = this.activeItem
      const {
        video_id,
        episode_id
      } = this.$props
      this.activeColor = index

      uni.$u.debounce(() => {

        uni.getProvider({
          service: 'payment',
          success(res) {
            const { provider } = res
            const providerStr = provider.toString()

            if (isVip) {
              // 会员充值
              orderCreateVip({
                package_id: id,
                recharge_type: 4, // 调起支付 1=支付宝 2=微信 3=苹果支付 4=抖音
                pay_aisle: 1, // 支付通道 1=小程序 2=app 3=苹果内购 4=h5
                video_id: video_id || undefined,
                episode_id: episode_id || undefined,
              }).then(data => {
                const { pay } = data
                _this.createPayment(providerStr, pay)
                
                // _this.createPaymentVirtually(pay)
              })
            } else {
              // 金币充值
              orderCreateCoin({
                package_id: id,
                recharge_type: 4, // 调起支付 1=支付宝 2=微信 3=苹果支付 4=抖音
                pay_aisle: 1, // 支付通道 1=小程序 2=app 3=苹果内购 4=h5
                video_id: video_id || undefined,
                episode_id: episode_id || undefined,
              }).then(data => {
                const { pay } = data
                _this.createPayment(providerStr, pay)

                // _this.createPaymentVirtually(pay)
              })
            }

          },
        }, 1000)

      })
    },

    // 发起支付
    async createPayment(providerStr, payParams) {
      const {
        order_id,
        order_token,
      } = payParams
      const _this = this
      const { shouldContinuePay } = this.$props

      uni.showLoading({
        title: '努力处理中...',
        mask: true
      })

      uni.requestPayment({
        provider: providerStr,
        orderInfo: {
          order_id,
          order_token
        },
        service: 5,
        success: function(res) {
          _this.activeColor = -1
          _this.$emit('success')
          _this.$emit('update:showPopup', false)
          console.log('success:' + JSON.stringify(res))
        },
        fail: function(err) {
          console.log(err)
          const { failType } = err
          _this.activeColor = -1

          if (failType === 'create') {
            // 创建支付失败时提示
            uni.showModal({
              content: err.msg,
              showCancel: false,
              confirmText: '确定'
            })
          } else if (failType === 'request') {
            // 请求支付失败时提示
            uni.$u.toast('请求支付失败')
          } else if (failType === 'result') {
            // 支付结果失败时提示
            uni.$u.toast('支付失败')
          } else {
            if (shouldContinuePay) _this.showContinuePay = true
            else uni.$u.toast('取消支付')
          }
          console.error('fail:' + JSON.stringify(err))
        },
        complete: function() {
          console.log('支付回调complete')
          uni.hideLoading()
        },
      })
    },

    // 微信虚拟支付
    createPaymentVirtually(payParams) {
      //    const signData = {
      //      offerId: '1450089368',
      //      buyQuantity: 1, // 购买数量
      //      env: 0, // 0-正式环境 1-沙箱环境
      //      currencyType: 'CNY',
      //      platform: 'android',
      //      // productId: '1450089368',
      //      // goodsPrice: 10,
      //      outTradeNo: 'C2023080815180625185419435',
      //      attach: 'test'
      //    }
      const _this = this
      const {
        signData,
        paySig,
        signature,
        mode
      } = payParams
      const signDataJSON = JSON.parse(signData)
      this.outTradeNo = signDataJSON.outTradeNo
      console.log(payParams)
      wx.requestVirtualPayment({
        ...payParams,
        success(res) {
          // console.log('虚拟支付success', res)
          _this.wxVirtualOrderQueryFn()
        },
        fail({
          errMsg,
          errCode
        }) {
          console.error(errMsg, errCode)
          uni.showModal({
            content: errMsg + '==' + errCode,
            showCancel: false,
            confirmText: '确定'
          })
          if (errCode === -2) {
            if (shouldContinuePay) _this.showContinuePay = true
            else uni.$u.toast('取消支付')
          }
        }
      })
    },

    wxVirtualOrderQueryFn() {
      if (!this.outTradeNo) return uni.$u.toast('缺少参数outTradeNo')

      wxVirtualOrderQuery({ order_no: this.outTradeNo }).then(() => {
				
        uni.hideLoading()
				
        this.activeColor = -1
        this.againQueryShow = false
        this.$emit('success')
        this.$emit('update:showPopup', false)
      }).catch(e => {
        this.againQueryShow = true
        this.wxVirtualOrderQueryFn()
      })
    },


    continuePayHandleCloase() {
      this.showContinuePay = false
    },

    continuePayHandleSubmit() {
      this.showContinuePay = false
      this.createOrder()
    }
  }
}
</script>

<style lang="scss" scoped>
	.title-nav {
		padding: 30rpx;
		display: flex;
		flex-direction: column;

		.title-panel {
			display: flex;
			align-items: center;
			justify-content: space-between;
		}

	}

	.episode-panel {
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex-wrap: wrap;
		border: 1px solid #FF9F70;
		border-radius: 16rpx;
		margin-top: 20rpx;
		margin-bottom: 20rpx;
		padding: 40rpx 24rpx;
	}


	.recharge-nav {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		padding: 0 30rpx 30rpx 30rpx;
		min-height: 400rpx;
	}

	.recharge_text {
		color: #ff894e;
		font-size: 26rpx;
		margin: 10rpx 20rpx;
		text-align: center;
	}

	.continue-pay-popup {
		.back-img {
			width: 620rpx;
			height: 840rpx;
		}

		.cloase-img {
			width: 42rpx;
			height: 42rpx;
			position: absolute;
			right: -16rpx;
			top: -16rpx;
		}

		.btn-img {
			width: 460rpx;
			height: 100rpx;
			position: absolute;
			bottom: 90rpx;
			left: 0;
			right: 0;
			margin: 0 auto;
		}

		.refuse-text {
			font-size: 28rpx;
			color: #961E16;
			position: absolute;
			bottom: 4%;
			left: 0;
			right: 0;
			margin: 0 auto;
			text-align: center;
		}
	}

	.tips-popup {
		/deep/ .u-popup__content {
			width: 90%;
			margin: 0 auto;
			border-radius: 16rpx;
			padding-bottom: 50rpx;
		}

		.tips-title {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 30rpx;
			color: $font-color;
			font-size: 32rpx;
			font-weight: bold;
			text-align: center;
			height: 100rpx;
			line-height: 100rpx;
		}

		.word {
			margin-bottom: 20rpx;
			padding: 0 30rpx;

			text {
				color: $font-color-2;
				font-size: 24rpx;
			}

			text:first-child {
				margin-right: 10rpx;
			}
		}
	}

	.tips-panel {
		padding-bottom: 20rpx;

		.word {
			height: 24rpx;
			line-height: 24rpx;
		}
	}
	
	.recharge-item-box {
		width: 48%;
	}

	.again-nav {
		width: 70vw;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 40rpx 0;
	}
</style>
